<template>
  <div class="tab-container">
    <el-tabs type="card" @input="tabClick" :value="activeName" class="nav-tab">
      <el-tab-pane v-for="item in tabList" :key="item.id" :label="item.title" :name="item.id.toString()" />
    </el-tabs>
    <div class="tab-context">
      <div class="left-nav-tab">
        <TabInfo />
      </div>
      <div class="map-view" ref="map"></div>
    </div>
  </div>
</template>
<script>
import TabInfo from './TabInfo.vue'
import Map from '@/assets/js/map.js'
import env from '@/assets/env'
import utils from '@/assets/js/utils'
import { mapGetters } from 'vuex'
window.iMap = null
let points = []
window.pointList = points
window._editPoint = null
// let iconObj = {}
export default {
  components: { TabInfo },
  computed: {
    ...mapGetters([
      'tabList',
      'activeTab',
      'selectTab',
      'activeFeature',
      'iconImageUrl',
      'activeIcon',
      'iconList',
      'iconObj',
      'newFeatures',
      'mapZoom',
      'editFeature'
    ]),
    activeName() {
      // console.log(this.activeTab, 'activeName')
      return this.activeTab === null ? null : this.activeTab.id.toString()
    }
  },
  created() {
    this.updateMarker = this.updateMarker.bind(this)
    this.deleteMarker = this.deleteMarker.bind(this)
  },
  mounted() {
    if (this.tabList.length === 0) {
      this.$store.dispatch('getTabList')
    }
    this.$store
      .dispatch('getIconList')
      .then(rst => {
        return this.$store.dispatch('getFeatureList', {})
      })
      .then(() => {
        // console.log(this.features, '点位信息列表')
        this.newFeatures.forEach(obj => {
          let feature = obj.feature
          let marker = this.createMarker(feature, obj.data)
          this.addMarker(marker)
        })

        // this.features.forEach(feature => {
        //   let marker = this.createMarker(feature)
        //   this.addMarker(marker)
        // })
        this.updateMapState()
      })

    iMap = new Map({
      id: this.$refs.map,
      center: env.CENTER,
      zoom: this.mapZoom,
      tileLayerUrl: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
      zoomControl: true,
      click: this.mapClick
    })

    iMap.getMap().on('zoomend', e => {
      this.updateMapState()
    })
  },
  methods: {
    tabClick(tabId) {
      // console.log(tab, event)
      this.$store.commit('selectTab', tabId)
    },
    mapClick(e) {
      // e.preventdefault()
      if (this.activeFeature) {
        let opt = utils.dataToMarkerOption(
          this.activeFeature,
          this.activeIcon,
          this.selectTab,
          e.latlng.lng,
          e.latlng.lat
        )
        opt.click = this.clickHandle
        opt.drag = this.dragHandle
        opt._update = this.updateMarker
        opt._del = this.deleteMarker
        let marker = iMap.createPoint(opt, this.activeFeature)
        // console.log(marker)
        // this.$store.commit('delMarkData', this.activeFeature)
        let f = utils.getFeature(opt)
        this.$store.commit('putFeatureList', {
          feature: this.activeFeature,
          point: f
        })
        this.setEditFeature(marker)
        this.addMarker(marker, true)
      }
    },
    createMarker(feature, data) {
      let icon = this.iconObj[feature.landmarkIcon_id]
      let item = {
        id: feature.id,
        longitude: feature.longitude,
        latitude: feature.latitude,
        width: feature.iconWidth,
        height: feature.iconHeight,
        maxzoom: feature.maxzoom,
        minzoom: feature.minzoom,
        imageUrl: icon == undefined ? null : env.FILE_URL + icon.normal,
        draggable: true,
        _edit: true,
        icon: icon,
        iconWidth: feature.iconWidth,
        iconHeight: feature.iconHeight,
        iconOpacity: feature.iconOpacity,
        landmarkMark_type: feature.landmarkMark_type,
        landmark_id: feature.landmark_id,
        landmarkIcon_id: feature.landmarkIcon_id,
        landmarkMark_id: feature.landmarkMark_id,
        landmarkMap_id: feature.landmarkMap_id,
        rotate: feature.rotate
      }

      item.click = this.clickHandle

      item.drag = this.dragHandle

      item._update = this.updateMarker

      item._del = this.deleteMarker

      let marker = iMap.createPoint(item, data)
      return marker
    },
    clickHandle(e) {
      let marker = e.target
      this.setEditFeature(marker)
    },
    dragHandle(e) {
      let marker = e.target
      let lnglat = marker.getLatLng()
      let data = {
        ...marker._data,
        longitude: lnglat.lng,
        latitude: lnglat.lat
      }
      marker._data = data
      this.setEditFeature(marker)
    },
    deleteMarker(data) {
      // 删除点位
      let index = points.findIndex(t => t._data.id == data.id)

      if (index > -1) {
        let marker = points[index]
        iMap.removeOverlay(marker)
        points.splice(index, 1)
        let cdata = marker._cdata
        this.$store.commit('deleteFeature', cdata.id)

        this.$store.commit('setEditFeature', null)

        // let landmarkMarkId = data.landmarkMark_id

        // this.$store.commit('cancelDelMarkData', landmarkMarkId)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      } else {
        this.$message.error('删除失败')
      }
    },
    updateMarker(data) {
      let marker = points.find(t => t._data.id == data.id)
      if (marker) {
        marker._data = { ...data }
        // 修改点位图片
        let obj = this.iconObj[data.landmarkIcon_id]
        let url = obj.normal
        if (
          this.editFeature &&
          this.editFeature.id == data.id &&
          obj.selected
        ) {
          url = obj.selected
        }
        console.log(url)
        this.changeIcon(marker, url)
        // 修改透明度
        let opacity = data.iconOpacity
        // console.log(opacity)
        marker.setOpacity(opacity)
        // 修改旋转角度
        let rotate = data.rotate
        // console.log(rotate)
        marker.setRotationAngle(rotate)
        this.$message.success('更新成功')
      } else {
        this.$message.error('更新失败')
      }
    },
    addMarker(marker, flag) {
      if (flag) iMap.addOverlay(marker)
      points.push(marker)
    },
    setEditFeature(marker) {
      window._editPoint = marker
      // console.log(marker._data)
      this.$store.commit('setEditFeature', { ...marker._data })
    },
    // 更新地图状态
    updateMapState() {
      let zoom = iMap.getZoom()
      this.$store.commit('setZoom', zoom)
      let tabId = this.selectTab.id
      let cid = this.editFeature == null ? null : this.editFeature.id
      points.forEach(point => {
        let id = point._data.id
        let typeId = point._data.landmarkMark_type // 类别
        let minzoom = point._data.minzoom
        let maxzoom = point._data.maxzoom
        if (
          id == cid ||
          (tabId == typeId && minzoom <= zoom && maxzoom >= zoom)
        ) {
          iMap.addOverlay(point)
        } else {
          iMap.removeOverlay(point)
        }
      })
    },
    changeIcon(marker, url) {
      let data = marker._data
      let icon = iMap.createIcon(env.FILE_URL + url, {
        iconSize: [data.width, data.height],
        iconAnchor: [data.width / 2, data.height / 2]
      })
      marker.setIcon(icon)
    }
  },
  watch: {
    selectTab(val) {
      this.updateMapState()
    },
    editFeature(val, oldval) {
      // 恢复回来
      if (oldval) {
        if (!(val && oldval.id == val.id)) {
          let icon = this.iconObj[oldval.landmarkIcon_id]
          if (icon && icon.normal) {
            let point = points.find(t => t._data.id == oldval.id)
            if (point) this.changeIcon(point, icon.normal)
          }
        }
      }
      // 变成选中图片
      if (val) {
        let icon = this.iconObj[val.landmarkIcon_id]
        if (icon && icon.selected) {
          let point = points.find(t => t._data.id == val.id)
          if (point) this.changeIcon(point, icon.selected)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.tab-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-flow: column nowrap;
  .nav-tab {
    flex-shrink: 0;
  }
  .tab-context {
    width: 100%;
    height: 100vh;
    display: flex;
    .left-nav-tab {
      width: 300px;
      height: 100%;
      flex-shrink: 0;
    }
    .map-view {
      width: 100%;
      height: 100%;
      background-color: bisque;
    }
  }
}
</style>
